//
//  T3FPolyline.swift
//  t3_map
//
//  Created by Cunhai Li on 2024/10/22.
//
import UIKit
import CoreLocation
import Bundle_Log

public enum T3FPolylineDashType: Int {
    case none = 0
    case square = 1
    case dot = 2
}

public enum T3FPolylineType: Int {
    case normal = 0 /// 标准线
    case multi = 1 /// 多彩线路(路况等)
}

public enum T3FPolylineCapType: Int {
    case butt = 0 ///< 普通头
    case square = 1 ///< 扩展头
    case arrow = 2 ///< 箭头
    case round = 3 ///< 圆形头
}

public enum T3FPolylineJoinType: Int {
    case bevel = 0 /// 实线
    case miter = 1 /// 方块样式
    case round = 2 /// 圆点样式
}

// MARK: - T3Polyline参数配置
public struct T3FPolylineOptions {

    /// 线条点串
    public var points: [CLLocationCoordinate2D]

    /// 是否可点击 - 默认 false
//    public var clickable = false
    
    public var fillColor: UIColor {
        return T3FColorUtil.hex(fillColorValue)
    }

    public var strokeColor: UIColor {
        return T3FColorUtil.hex(strokeColorValue)
    }

    public var fillColorValue: String = "#1ab587"

    public var strokeColorValue: String = "#1ab587"

    public var miterLimit: Double = 2.0
    public var lineType: T3FPolylineType = .normal
    public var dashType: T3FPolylineDashType = .none
    public var capType: T3FPolylineCapType = .butt
    public var joinType: T3FPolylineJoinType = .bevel
    /// 线条宽度
    public var width: Double = 10
    /// 唯一标识符，路线的唯一id，使用时不要重复；如果重复，在移除时会向所有该标识符的路线移除；
    public var identifier: String

    /// ------------------------- 彩色路线数据 --------------------------------
    /// 数据格式[38-1, 53-0]
    public var traffic: [String]?
    
    public var isSelected: Bool = false
    
    /// 存放路况值对应的颜色
    public var lineColors: [UIColor] = []
    /// 存放路况值对应的图片
    public var lineImages: [UIImage] = []
    /// 路况的索引的数据
    public var lineIndexes: [Int] = []
    /// 路况索引对应的值的数组
    public var lineImagesIndexs: [Int] = []

    public init(points: [CLLocationCoordinate2D], identifier: String) {
        self.points = points
        self.identifier = identifier
    }

    init?(from jsonString: String) {
        do {
            let json = try T3FJsonUtil.toJson(jsonString)
            self.init(from: json)
        } catch (let error) {
            T3Log.error("polyline初始化异常，error = \(error.localizedDescription)")
            return nil
        }
    }

    init?(from json: [String: Any]) {
        guard let uid = json["uid"] as? String else { return nil }
        guard let points = json["points"] as? Array<Array<Double>> else { return nil }
        guard let style = json["style"] as? [String: Any] else { return nil }
        guard let width = style["width"] as? Double else { return nil }
        guard let fillColorValue = style["fillColorValue"] as? String else { return nil }
        guard let strokeColorValue = style["strokeColorValue"] as? String else { return nil }

        self.points = points.map({ value in
            return CLLocationCoordinate2D(latitude: value[1], longitude: value[0])
        })
        self.identifier = uid
        self.width = width
        self.fillColorValue = fillColorValue
        self.strokeColorValue = strokeColorValue

        if let value = style["miterLimit"] as? Double {
            self.miterLimit = value
        }

        if let value = style["lineDashType"] as? Int, let type = T3FPolylineDashType(rawValue: value) {
            self.dashType = type
        } else {
            self.dashType = .none
        }
        if let value = style["lineCapType"] as? Int, let type = T3FPolylineCapType(rawValue: value) {
            self.capType = type
        }
        if let value = style["lineJoinType"] as? Int, let type = T3FPolylineJoinType(rawValue: value) {
            self.joinType = type
        }
        if let value = style["lineType"] as? Int, let type = T3FPolylineType(rawValue: value) {
            self.lineType = type
        }
        
        self.isSelected = (style["isSelected"] as? Bool) ?? false;
        

        /// ------------------------- 彩色路线数据解析 --------------------------------
        if self.lineType == .multi {
            var lineImages: [UIImage] = []
            var lineColors: [UIColor] = []
            for travel in T3FPolylineColorMold.allCases {
                if isSelected {
                    lineImages.append(travel.selectImage ?? UIImage())
                    lineColors.append(travel.selectColor)
                } else {
                    lineImages.append(travel.unSelectImage ?? UIImage())
                    lineColors.append(travel.unSelectColor)
                }
            }
            self.lineImages = lineImages
            self.lineColors = lineColors
            
            if let trafficStr = style["traffic"] as? String, trafficStr.isEmpty != true {
                traffic = trafficStr.components(separatedBy: ";")
                var imagesIndexs: [Int] = []
                var lineIndexes: [Int] = []

                if let traffics = traffic, !traffics.isEmpty {
                    for perTraffic in traffics {
                        let perTraffics = perTraffic.components(separatedBy: "-")
                        if perTraffics.count == 2  {
                            let tmcIndex: Int = Int(perTraffics[0]) ?? 0
                            let tmcTraffic: T3FPolylineColorMold = T3FPolylineColorMold(rawValue: Int(perTraffics[1]) ?? 1) ?? .clear

                            imagesIndexs.append(tmcTraffic.rawValue)
                            lineIndexes.append(tmcIndex)
                        }
                    }
                }
                
                self.lineIndexes = lineIndexes
                lineImagesIndexs = imagesIndexs
            } else {
                /// 如果路况为空，兜底畅通路况
                lineIndexes = [max(0, points.count - 1)]
                lineImagesIndexs = [T3FPolylineColorMold.clear.rawValue]
                T3Log.error("polyline路况数据为空")
            }
        }
    }
}


// MARK: - T3Polyline
public protocol T3FPolyline {
    /// 参数配置
    var options: T3FPolylineOptions { get }

    func update(options: T3FPolylineOptions)
}
